package me.xinping.libs.recording

import android.media.MediaPlayer
import android.net.Uri
import me.xinping.libs.base.BaseApp
import me.xinping.libs.utils.ContextUtils
import me.xinping.libs.utils.CountTimer
import java.io.File

/**
 * 录音播放器.
 * <p>
 * Date 2018/12/4
 * @author fanxinping_cd@keruyun.com
 */
class RecorderPlayer private constructor() {
    var playingListener: OnPlayingListener? = null

    private var mediaPlayer: MediaPlayer? = null
    private var countTimer: CountTimer = CountTimer()
    private var currentPlayFilePath: String? = null

    private fun initPlayer(filePath: String) {
        mediaPlayer = MediaPlayer.create(BaseApp.instance, Uri.fromFile(File(filePath)))
        mediaPlayer?.setVolume(DEFAULT_VOLUME, DEFAULT_VOLUME)
        mediaPlayer?.isLooping = false
        mediaPlayer?.setOnCompletionListener { stop() }
        mediaPlayer?.setOnPreparedListener {
            it.start()
            playingListener?.onStart(currentPlayFilePath)
        }
    }

    /**
     * 播放录音
     * @param filePath 录音文件
     * @param progress 从指定的进度处开始播放，默认从头开始播放
     */
    fun play(filePath: String, progress: Int = 0) {
        if (filePath.isEmpty() || !File(filePath).exists())
            throw IllegalArgumentException("play record file path of $filePath is not exist,please check!!!")
        currentPlayFilePath = filePath
        stop()
        initPlayer(filePath)
        mediaPlayer?.seekTo(progress)
        countTimer.start {
            ContextUtils.runOnUIThread {
                val seconds = (mediaPlayer?.currentPosition ?: -1) / 1_000
                playingListener?.onProgress(currentPlayFilePath, seconds)
            }
        }
    }

    fun pause() {
        mediaPlayer?.pause()
    }

    fun resume() {
        mediaPlayer?.start()
    }

    fun stop() {
        if (mediaPlayer?.isPlaying == true) {
            mediaPlayer?.stop()
            mediaPlayer?.reset()
            mediaPlayer?.release()
            mediaPlayer = null
        }
        countTimer.stop()
        playingListener?.onStop(currentPlayFilePath)
    }

    interface OnPlayingListener {
        /**
         * 开始播放
         */
        fun onStart(filePath: String?)

        /**
         * 播放结束
         */
        fun onStop(filePath: String?)

        /**
         * 播放进度，单位：秒
         */
        fun onProgress(filePath: String?, seconds: Int)
    }

    companion object {
        val instance: RecorderPlayer by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { RecorderPlayer() }
        /**
         * 默认音量
         */
        private const val DEFAULT_VOLUME = 1.0f
    }
}